package com.album.activity.pageView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Entity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.activity.SetstateManager; 
import com.album.activity.adapter.MyPhotoAdapter;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.activity.pageView.CasualLookView.loadingUserImage;
import com.album.activity.pageView.MyFriendsView.ListAdapter;
import com.album.bean.ErrorInfo;
import com.album.bean.FriendsInfo;
import com.album.bean.ImageBean;
import com.album.bean.PicinfoList;
import com.album.bean.RondomUser;
import com.album.http.HttpRequest;
import com.album.task.AddFriendTask;
import com.album.task.DownImageTask;
import com.album.task.GetFriendsTask;
import com.album.task.GetPicinfolistTask;
import com.album.task.GetRandomPicinfolistTask;
import com.album.task.GetUsersRandom;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.utils.AndroidUtils;
import com.album.utils.CommonUtil;
import com.album.utils.Config;
import com.album.utils.MyLog;
import com.album.utils.down.AsyncImageLoader;
import com.album.utils.down.ImageUtil;
import com.album.utils.down.MyImageAdapter;
import com.album.utils.down.ImageAndText;
import com.album.utils.down.AsyncImageLoader.ImageCallback;
import com.album.utils.down.ImageAndTextListAdapter;
import com.google.gson.Gson;

public class CopyOfMyFriendsView extends Page{
	private static String TAG = "CasualLookView";
	 
	/**
	 * 好友头像
	 */ 
	private ListView casualListView;
	private HorizontalScrollView scrollView;
	private Gson gson;
	private String username;//用户名

	private static final int FRIEND_INFO = 111;
	private static final int FRIEND_FAIL = 112;
	private static final int FRIEND_NO = 115;
	
	private static final int PICINFOLIST_RE_MYPTO_IMAGE = 117;
	private static final int PICINFOLIST_DOWN_IMAGE_FAIL = 118;
	private static final int PICINFOLIST_INFO = 119;
	private static final int PICINFOLIST_INFO_FAIL = 200;

	private static final int TIME_OUT = 11;
	private static final int INTENT_ERROR = 12;
	private static final int HTTP_ERROR = 13;
	private ProgressDialog dialog_1;
	private Context ctx;
	private boolean loding_view_flgs = false;	//刷新view 避免重复
	/*
	 * 存放用户头像、昵称、时间、相片
	 */
	private List<FriendsInfo> friendList = new ArrayList<FriendsInfo>();
	public CopyOfMyFriendsView(PageManager manager) {
		super(manager);
		// TODO Auto-generated constructor stub
	}
	//好友图片url 
	/*
	 * 存放用户头像、昵称、时间、相片
	 */
	private List<RondomUser> userRanList = new ArrayList<RondomUser>();
	private ListAdapter adapterTest;
	
	@Override
	public View getView() {
		Log.i(TAG, "@Override getView");
		return casualListView;
	}	
	@Override
	public void onCreate(Object extra) {
		super.onCreate(extra);
		 
		if(userRanList != null && userRanList.size()>0){
			userRanList.clear();
		}  
		ctx = manager.getContext();
		SetstateManager.setRefresState(CopyOfMyFriendsView.class, manager);
		username = CommonUtil.getUserName(ctx);
		
		if(SetstateManager.infoList!= null&&SetstateManager.infoList.size()>0){
			SetstateManager.infoList.clear();
		} 
		
		if(!loding_view_flgs){
			casualListView = new ListView(ctx);
			casualListView.setBackgroundColor(Color.BLACK);
			casualListView.setCacheColorHint(0x00000000);
			casualListView.setScrollbarFadingEnabled(false);
			casualListView.setVerticalScrollBarEnabled(true);
			adapterTest = new ListAdapter(manager.getContext());
		    casualListView.setAdapter(adapterTest);
		}
		
	    
		 //获取好友列表
        getFriends(username);
        casualListView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				MyLog.info(getClass(), "单击我的好友itme");
				CommonUtil.setFriendName(friendList.get(position).slave);
				CommonUtil.setFriendNick(friendList.get(position).nick);
				try {
					SetstateManager.setBacktoState(MyFriendsView.class, manager);
					SetstateManager.setRefresState(MyFriendsPhotoView.class, manager);
					manager.activePage(MyFriendsPhotoView.class, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		if(!loding_view_flgs)
			loding_view_flgs = true;
		
			MyLog.debug(getClass(), "===================loding_view_flgs====================:"+loding_view_flgs);
	}
	/**
	 * 获取好友列表
	 * @author Administrator
	 */
	private void getFriends(String username){
		String rspString = null;
		if(gson == null)
		  gson = new Gson();
		Task task = new GetFriendsTask(ctx,username,1,20,new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
			}
			@Override
			public void CallBack(String rspString) {
				try {
					List<String> listUserImageUrl= new ArrayList<String>();
					MyLog.info(getClass(), "jsonData:" + rspString);
					rspString = "[" + rspString + "]";
					JSONArray array = new JSONArray(rspString.toString());
					JSONArray array_data;
					JSONObject obj = array.getJSONObject(0);
					if (obj.getBoolean("msg")) {
						String res_data = obj.getString("data");
						MyLog.info(getClass(),
								"data:" + res_data.toString());
//						if("[]".equals(res_data.toString())){
//							handler.sendEmptyMessage(FRIEND_NO);
//							return;
//						}
						array_data = new JSONArray(res_data.toString());
						for (int i = 0; i < array_data.length(); i++) {
							FriendsInfo user = new FriendsInfo();
							JSONObject obj_data = array_data.getJSONObject(i);
							String friendname = obj_data.getString("slave");
							user.setMaster(obj_data.getString("master"));
							user.setIcon(obj_data.getString("icon"));
							user.setCreated(obj_data.getString("created"));
							user.setNick(obj_data.getString("nick"));
							user.setSlave(friendname);
							user.setStatus(obj_data.getString("status"));
							friendList.add(user);
							listUserImageUrl.add(friendname);	//拿好友图片
							 
							Message heandms = new Message();
							heandms.obj=user;
							heandms.what = FRIEND_INFO; 
							//sendMessageAtFrontOfQueue
							handler.sendMessageAtFrontOfQueue(heandms);	//立即发送Message到队列，而且是放在队列的最前面  
						}
						if (dialog_1 != null && dialog_1.isShowing()){
							dialog_1.dismiss();
						}
						
						Message ms = new Message();
						ms.obj=listUserImageUrl;
						ms.what = PICINFOLIST_INFO;
						handler.sendMessage(ms);
						
					} else {
						RondomUser info=new RondomUser();
						info.setErrCode(obj.getString("errCode"));
						Message ms = new Message();
						ms.what = FRIEND_FAIL;
						ms.obj = info;
						handler.sendMessage(ms);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(INTENT_ERROR);
			}
		});
		dialog_1 = ProgressDialog.show(ctx, "", ctx.getText(R.string.get_frineds), true);
		dialog_1.setCancelable(true);
		task.doTask(task);
	}
//	/**
//	 * 获取相册列表
//	 */
//	private void getPicinfolist(final String username) {
//		MyLog.debug(getClass(), "__________________getPicinfolist username:"+username);
//		if (gson == null) {
//			gson = new Gson();
//		}
//		Task task = new GetRandomPicinfolistTask(ctx,username, null,
//				new ICallBack() {
//					@Override
//					public void CallBack(String imageUrl, Bitmap bm) {
//					}
//					@Override
//					public void CallBack(String rspString) {
//						// TODO Auto-generated method stub
//						Map<String, List<ImageBean>> imagelistMap = new HashMap<String, List<ImageBean>>();
//						HashMap<String, List<String>> imageIdMap = new HashMap<String, List<String>>();
////						MyLog.info(getClass(), "jsonData:" + rspString);
//						rspString = "[" + rspString + "]";
//						JSONArray array;
//						JSONArray array_data;
//						List<PicinfoList> picinfoList;
//						List<ImageBean> imangeList;
//						List<String> imageId;
//						try {
//							int j=0; //获取单个好友图片个数，默认为4张图片
//							picinfoList = new ArrayList<PicinfoList>();
//							imangeList = new ArrayList<ImageBean>();
//							imageId = new ArrayList<String>();
//							array = new JSONArray(rspString.toString());
//							JSONObject obj = array.getJSONObject(0);
//							if (obj.getBoolean("msg")) {
//								String res_data = obj.getString("data");
//								if(!"[]".equals(res_data.toString())){
////									MyLog.info(getClass(), data:" + res_data.toString());
//									array_data = new JSONArray(res_data.toString());
//									int length = array_data.length();
//									for (int i = 0; i < length; i++) {
//										JSONObject obj_data = array_data.getJSONObject(i);
////										MyLog.info(getClass(),"exif:" + obj_data.toString());
//										PicinfoList info = new PicinfoList();
////										info.setFileid(obj_data.getString("fileid"));
//										info.setId(obj_data.getString("id"));
//										info.setPassport(obj_data.getString("passport"));
////										info.setPublic_(obj_data.getString("public"));
////										info.setTypeid(obj_data.getString("typeid"));
//										info.setUpload_time(obj_data.getString("upload_time"));
////										info.setTitle(obj_data.getString("title"));
////										info.setContent(obj_data.getString("content"));
////										info.setViews(obj_data.getString("views"));
////										info.setScore(obj_data.getString("score"));
////										info.setBlock(obj_data.getString("block"));
////										info.setArea(obj_data.getString("area"));
////										info.setCoordinate(obj_data.getString("coordinate"));
//										info.setPath_image(obj_data.getString("web_path"));
////										info.setHash_code(obj_data.getString("hash_code"));
////										MyLog.info(getClass(), "web_path:" + info.getPath_image());
//										//ProviderUtil.insertOrUpdatePicinfoList(manager.getContext(), info);
//										picinfoList.add(info);
//										if(j!=4){
//											ImageBean imageBean = new ImageBean();
//											if(info.getPath_image()!=null){
//												String filename = info.getPath_image().substring(info.getPath_image().lastIndexOf("/")+1);
//												filename = filename.substring(0, filename.length()-4)+"_75_75."+filename.substring(filename.length()-3,filename.length());
//												
//												String imageUrul = Config.TyDownHttp+info.getPassport()+"/"+filename;
////												MyLog.info(getClass(),"random imageUrul:" + imageUrul);
//												imageBean.setImageUrl(imageUrul);
//												imageBean.setPirId(info.getId());
//												imangeList.add(imageBean);
//												//imageId.add(info.getId());
//												j++;
//											}
//										}
//										 
//										imagelistMap.put(username, imangeList);
//									} 
//								}
//								else{	// not 
//									//imagelistMap.put(username, new ArrayList());
////									Message ms = new Message();
////									ms.what = PICINFOLIST_INFO_NOT;
////									ms.obj = username;
////									handler.sendMessage(ms);
//								}
//								Message ms = new Message();
//								ms.what = PICINFOLIST_INFO_NOT;
//								ms.obj = imagelistMap;
//								handler.sendMessage(ms);
//								
//							} else {
//								PicinfoList info = new PicinfoList();
//								info.setErrCode(obj.getString("errCode"));
//								Message ms = new Message ();
//								ms.what = PICINFOLIST_INFO_FAIL;
//								ms.obj = info;
//								handler.sendMessage(ms);
//							}
//							
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}
//					}
//					@Override
//					public void TimeOut() {
//						//网络超时处理
//						handler.sendEmptyMessage(TIME_OUT);
//					}
//					@Override
//					public void HttpError(int errorCode) {
//						// TODO Auto-generated method stub
//						handler.sendEmptyMessage(INTENT_ERROR);
//					}
//				});
//		task.doTask(task);
//	}
	  /**
	    * 处理ui界面
	    */
	   private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				try {
					switch (msg.what) {
//					case 2:
//						//Log.w("---------------", "不断执行"+msg.what);
//						scrollView.smoothScrollBy(1500, 0);
//						//scrollView.scrollBy(150, 0);
//						break;
					case FRIEND_INFO://获取到好友信息
						FriendsInfo user = (FriendsInfo)msg.obj;
						adapterTest.setDataUserSetChange(user);
						break;
					case FRIEND_NO: //没有好友信息
						MessageDialog.showToast(ctx, false,
								ctx.getString(R.string.no_friend));
						if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
//						adapterTest = new ListAdapter(ctx,FRIEND_NO);
//					    casualListView.setAdapter(adapterTest);
						break;
					case FRIEND_FAIL: //获取好友信息失败
						RondomUser infoFail = (RondomUser) msg.obj;
						MessageDialog.showToast(ctx, false,
								ErrorInfo.errorMap.get(infoFail.getErrCode()));
						if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
						break;
					case PICINFOLIST_INFO:
						List<String> userNamelist =(List<String>)msg.obj;
						new loadingUserImage().execute(userNamelist);
						break;
					case PICINFOLIST_INFO_FAIL:// 获取相册失败
						PicinfoList picInfo_fail = (PicinfoList)msg.obj;
						MessageDialog.showToast(ctx, false,ErrorInfo.errorMap.get(picInfo_fail.getErrCode()));
						break;
					case PICINFOLIST_RE_MYPTO_IMAGE:
						//做图片显示操作
						Bitmap bm = (Bitmap)msg.obj;
						//刷新界面
						adapterTest.notifyDataSetChanged();
						casualListView.setAdapter(adapterTest);
						break;
					case PICINFOLIST_DOWN_IMAGE_FAIL://下载图片失败
						//MessageDialog.showToast(ctx, false, ctx.getString(R.string.imagedown_doing_fail));
						break;
					case TIME_OUT://超时
						if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
						MessageDialog.showToast(ctx, false, ctx.getString(R.string.int_timeout));
						break;
					case INTENT_ERROR://网络错误
						if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
						MessageDialog.showToast(ctx, false, ctx.getString(R.string.int_error));
						break;
						}
				} catch (Exception e) {
				    e.printStackTrace();
				}
				}
		};
	public Bitmap getBitmap(RondomUser info ){
				Bitmap bm =null;
//				MyLog.info(getClass(), "随便看看头像名字："+info.getHead_path());
				String url = Config.TyDownHttp+CommonUtil.getHeadImage(info.getPassport(),info.getHead_path());
//					bm=	CommonUtil.loadBitMap(ctx, url);//下载头像
//					MyLog.info(getClass(), "随便看看头像："+bm);
				try {
					bm = ImageUtil.getBitmapFromUrl(url);
				} catch (Exception e) { return null;
				}
				if(bm == null){
					InputStream is = manager
							.getContext()
							.getResources()
							.openRawResource(
									R.drawable.inithead);
					bm = BitmapFactory.decodeStream(is);
				}
			
		return bm;
	}
    public class ViewHolder{
    	 ImageView userHead;
			TextView userName;
			TextView time;
			ImageView lookpto;
			ImageView addfriend;
			GridView gridView;
			LinearLayout Layout;
			LinearLayout imageLayout;	
			LinearLayout layout_center; 
    }
    
    class ImageAdapter extends BaseAdapter{  
    	  //声明Context   
    	  private Context context;  
    	  private int i=0;
    	  //图片源数组   
    	  private Integer[] imageInteger = new Integer[4]; 
    	  
    	  public ImageAdapter(Context c,int i){  
     	     this.context = c;   
    	     if(i==1){
    	    	 Integer[] imageInteger = new Integer[]{  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading};
    	    	 		this.imageInteger = imageInteger;
    	     }else{
    	    	 Integer[] imageInteger2 = new Integer[]{  
    	    		 R.drawable.icon,  
         	         R.drawable.icon,  
         	         R.drawable.icon,  
         	         R.drawable.icon};
    	    	 		this.imageInteger = imageInteger2;
    	     }
    	  }  
    	 
    	  @Override 
    	  //获取图片的个数  
    	  public int getCount() {  
    	     return imageInteger.length;  
    	  }  
    	 
    	  @Override 
    	  //获取图片在库中的位置  
    	  public Object getItem(int position) {  
    	 
    	     return position;  
    	  }  
    	 
    	  @Override 
    	  //获取图片在库中的位置  
    	  public long getItemId(int position) {  
    	     // TODO Auto-generated method stub  
    	     return position;  
    	 }  
    	 
    	  @Override 
    	  public View getView(int position, View convertView, ViewGroup parent) {  
             final ImageView imageView;           
             if (convertView == null) {      
                 imageView=new ImageView(context);
                 imageView.setLayoutParams(new GridView.LayoutParams(70, 70));  
                 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);   
                 convertView = imageView;   
        	     imageView.setImageResource(imageInteger[position]);
             } 
    	     //设置布局 图片128x192显示   
    	     return convertView;  
    	  }  
    	}  
	 public class ListAdapter extends BaseAdapter{
		 
		 	private String imageUrl= "http://img2.vipshop.com/upload/merchandise/4787/ANTA-1033383-2-5.jpg";
	    	private Context mContext;
	        private AsyncImageLoader imageLoader;
	        //默认头像 
	        private Drawable defaultDrawable = null;	
	        //好友图片Url
	        private List<Map<String, List<ImageBean>>> user_imagelist = new ArrayList<Map<String, List<ImageBean>>>();
	        
	        //用户信息
	    	private List<FriendsInfo> userRanList = new ArrayList<FriendsInfo>(); 
	    	
	    	private ListAdapter(Context context){
	    		mContext = context; 
	    		if(defaultDrawable==null){
	    			defaultDrawable =  mContext.getResources().getDrawable(R.drawable.inithead);
	    		}
	    	}
			public void setDataSetChangedImageUrl(Map<String, List<ImageBean>> imageUrl_list){
				user_imagelist.add(imageUrl_list);
		    	notifyDataSetChanged();
			}
			public void setDataUserSetChange(FriendsInfo user){ 
				userRanList.add(user);
		    	notifyDataSetChanged();
		    }
			
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;  
			if (convertView == null) {
				imageLoader = new AsyncImageLoader();
				holder = new ViewHolder();  
				LayoutInflater inflater  = LayoutInflater.from(mContext); 
				convertView = inflater.inflate(R.layout.casual_image_list, null);
				holder.Layout = (LinearLayout) convertView .findViewById(R.id.LinearLayout_list);
				holder.userHead = (ImageView) convertView .findViewById(R.id.image_head);
				holder.userName = (TextView) convertView .findViewById(R.id.user_name);
				holder.time = (TextView) convertView .findViewById(R.id.user_time);
				holder.lookpto = (ImageView) convertView .findViewById(R.id.lookpto);
				holder.addfriend = (ImageView) convertView .findViewById(R.id.addfriend);
				holder.layout_center =(LinearLayout)convertView .findViewById(R.id.layout_center); 
				holder.gridView = (GridView)convertView.findViewById(R.id.gridView);
				holder.gridView.setGravity(Gravity.CENTER);// 位置居中  
				convertView.setTag(holder); 
			}else{
				holder = (ViewHolder) convertView.getTag();
			} 
			try {
				
				//设置头像
//				if (headBmList != null && headBmList.size() > 0) {
//					Bitmap bm = headBmList.get(position);
//					if(bm!=null){
//						bm = Bitmap.createScaledBitmap(bm, 40, 40, true);// 预先缩放，避免实时缩放，可以提高更新率
//						holder.userHead.setImageBitmap(bm);
//					}else{
//						holder.userHead.setImageBitmap(defaultHeadbm);
//					}
//				} 
				String ranImageUrl = userRanList.get(position).getIcon();
				MyLog.debug(getClass(), "ranImageUrl:"+ranImageUrl);
				
				if(ranImageUrl!=null && ranImageUrl!=""){	//解析JSON 此路径为 null
					defaultDrawable = imageLoader.loadDrawable(ranImageUrl, new ImageCallback() {  

	                     public void imageLoaded(Drawable imageDrawable, String imageUrl) {  
	                         if(imageDrawable!=null)
	                        	 holder.userHead.setImageDrawable(imageDrawable);  
	                     }  
	                 });   
				}
				
				holder.userHead.setImageDrawable(defaultDrawable);
				 
				if(user_imagelist!=null && user_imagelist.size()>0){ 
					Map<String, List<ImageBean>> mapBean = user_imagelist.get(position);
					List<ImageBean> imageBeanlist=null;
					String userName=null ;
					for(Entry<String, List<ImageBean>> entry: mapBean.entrySet()) {  
						userName = entry.getKey();
						imageBeanlist = entry.getValue();
					}  
//					SetstateManager.setUsernameList(userName);
					int imageSize = imageBeanlist.size(); 
//					MyLog.debug(getClass(), "position:"+position+" userName:"+userName+" imageList:"+imageSize);
					
					MyImageAdapter myimggeAdapter = new MyImageAdapter(mContext, imageBeanlist);
					holder.gridView.setAdapter(myimggeAdapter);
//					imageAdapter.notifyDataSetChanged(); 
						
					holder.gridView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int pic, long id) {
						
						// Eugene:调用图片编辑器
						MyLog.info(getClass(), "Eugene: Invoking PicInfoView");
						//SetstateManager.setPicUserState(userName);
						//SetstateManager.setPicListState(SetstateManager.infoList.get(pic).getId());
						try {
							manager.activePage(PicinfoView.class, null);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}});
				}
				if(SetstateManager.imageIdMapList!=null && SetstateManager.imageIdMapList.size()>0){ 
					Map<String, List<String>> map = SetstateManager.imageIdMapList.get(position);
					List<String> imageId=null;
					String userName=null ;
					for(Entry<String, List<String>> entry: map.entrySet()) {  
						userName = entry.getKey();
						imageId =entry.getValue();
						SetstateManager.setUsernameList(userName); 
					}  
				}

			}catch (Exception e) { MyLog.debug(getClass(), e.getMessage()); 
			}catch(OutOfMemoryError er){ return null;
			} 
		
			//长按操作
			holder.userHead.setOnLongClickListener(new View.OnLongClickListener() {
					
				@Override
				public boolean onLongClick(View v) { 
					MyLog.debug(getClass(), "onLongClick...");
					holder.layout_center.setVisibility(View.VISIBLE);
					return true;
				}
			});
			holder.userName.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					holder.layout_center.setVisibility(View.VISIBLE);
					return true;
				}
			});
			holder.Layout.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Log.i(TAG, "单击消失");
						if(holder.layout_center.getVisibility()==View.VISIBLE)
							holder.layout_center.setVisibility(View.GONE); 
					}
				});
				//点击查看相片
			holder.lookpto.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						try {
							manager.activePage(PicinfoView.class, null);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			
				//设置昵称
			    if (userRanList != null && userRanList.size() > 0){
			    String nick = userRanList.get(position).getNick();
				if(nick!=null &&! "".equals(nick))
					holder.userName.setText(userRanList.get(position).getNick());
			    }else{
			    	String username = userRanList.get(position).getSlave();
			    	if(!"pconline".equals(username))
			    	holder.userName.setText(userRanList.get(position).getSlave().substring(0,7)+"****");
			    	else
			    		holder.userName.setText(userRanList.get(position).getSlave());
			    }
				//设置时间
					holder.time.setText("9月1日");
				//设置四张相片
			return convertView;
		} 
//		public void setDataSetChangedBitmap(Bitmap bitmap){ 
//			userRanList.add(bitmap);
//	    	notifyDataSetChanged();
//	    }
//		
		@Override
		public int getCount() {
			return (userRanList !=null && userRanList.size()>0) ? userRanList.size():0;  
		}
		@Override
		public Object getItem(int position) {
			return (userRanList !=null && userRanList.size()>0) ? userRanList.get(position): null; 
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		
	}
	 
	 //异步加载好友图片信息同时更新UI
	 class loadingUserImage extends AsyncTask<List<String>,Object,Integer>{ 
	 		
	 		int returnStatus=0;
	 		@Override
	 		protected Integer doInBackground(List<String>... params) {
	 			// TODO Auto-generated method stub
	 			try {  
	 				List<String> usernameList = params[0];
	 				
	 				for(String userName :usernameList ){
	 					String strUrl =Config.TyHttp + Config.TyPicHttp+"picinfolist?type="+"&passport="+userName
	 					+"&attribute=";
	 					String rspString = HttpRequest.sendDataPost(ctx,strUrl, null,null);
	 						Map<String, List<ImageBean>> imagelistMap = new HashMap<String, List<ImageBean>>();
							HashMap<String, List<String>> imageIdMap = new HashMap<String, List<String>>();
//							MyLog.info(getClass(), "jsonData:" + rspString);
							rspString = "[" + rspString + "]";
							JSONArray array;
							JSONArray array_data;
							List<PicinfoList> picinfoList;
							List<ImageBean> imangeList;
							List<String> imageId;
							try {
								int j=0; //获取单个好友图片个数，默认为4张图片
								picinfoList = new ArrayList<PicinfoList>();
								imangeList = new ArrayList<ImageBean>();
								imageId = new ArrayList<String>();
								array = new JSONArray(rspString.toString());
								JSONObject obj = array.getJSONObject(0);
								if (obj.getBoolean("msg")) {
									String res_data = obj.getString("data");
									if(!"[]".equals(res_data.toString())){
//										MyLog.info(getClass(), data:" + res_data.toString());
										array_data = new JSONArray(res_data.toString());
										int length = array_data.length();
										for (int i = 0; i < length; i++) {
											JSONObject obj_data = array_data.getJSONObject(i); 
											PicinfoList info = new PicinfoList(); 
											info.setId(obj_data.getString("id"));
											info.setPassport(obj_data.getString("passport")); 
											info.setUpload_time(obj_data.getString("upload_time"));
											info.setPath_image(obj_data.getString("web_path"));
											picinfoList.add(info);
											if(j!=4){
												ImageBean imageBean = new ImageBean();
												if(info.getPath_image()!=null){
													String filename = info.getPath_image().substring(info.getPath_image().lastIndexOf("/")+1);
													filename = filename.substring(0, filename.length()-4)+"_75_75."+filename.substring(filename.length()-3,filename.length());
													
													String imageUrul = Config.TyDownHttp+info.getPassport()+"/"+filename;
//													MyLog.info(getClass(),"random imageUrul:" + imageUrul);
													imageBean.setImageUrl(imageUrul);
													imageBean.setPirId(info.getId());
													imangeList.add(imageBean); 
													j++;
												}
											}
											imagelistMap.put(userName, imangeList);
										} 
									}
									int imageCount = imangeList.size();
									MyLog.debug(getClass(), "用户:"+userName+" 图片个数:"+imangeList.size());
									if(imageCount>0){
										publishProgress(imagelistMap);
									}else{
										imagelistMap.put(userName, new ArrayList<ImageBean>());
										this.publishProgress(imagelistMap);
									}
								} else {
									this.publishProgress(returnStatus);
								}
								
							} catch (JSONException e) { e.printStackTrace();
							}
	 				}
	 				
	 			} catch (OutOfMemoryError e) {
	 				e.printStackTrace();
	 				return 1;
	 			}
	 			return 0;
	 		}
	 		
	 		@Override
	 		protected void onProgressUpdate(Object... values) {
	 			// TODO Auto-generated method stub 
	 			if(values!=null){
	 				MyLog.debug(getClass(), "values:"+values[0]);
	 				Map<String, List<ImageBean>> imagelistMap =(HashMap<String, List<ImageBean>>)values[0];
					List<ImageBean> imageUrlList = null ;
					for(Entry<String, List<ImageBean>> entry: imagelistMap.entrySet()) {  
						imageUrlList = entry.getValue();
						   MyLog.info(getClass(), ">>>>>>>>>>>>>>>>>>>>>userName:"+entry.getKey()+"-----imageListSize--:"+entry.getValue().size());
					} 
					adapterTest.setDataSetChangedImageUrl(imagelistMap);
	 			}
	 		}
	 		@Override  
	 	    protected void onCancelled() {  
	 			super.onCancelled();  
	 	    }  
	 		 
	 		@Override
	 		protected void onPostExecute(Integer result) {
	 			// TODO Auto-generated method stub 
	 			if(result==0){ 
	 			}
	 		}
	 	}
	 
	 class loadingUserRondom extends AsyncTask<List<RondomUser>,Bitmap,Integer>{   
		 
		 @Override
		 protected Integer doInBackground(List<RondomUser>... params) {
			 List<RondomUser> RondomUserlist = params[0];
			 Bitmap bm =null;
			 InputStream is = manager
				.getContext()
				.getResources()
				.openRawResource(
						R.drawable.inithead);
			 for(RondomUser info : RondomUserlist){
				try {
					 MyLog.info(getClass(), "随便看看头像名字："+info.getHead_path());
					 if(info.getHead_path()!=null){
						 bm = CommonUtil.loadBitMap(ctx, Config.TyDownHttp+CommonUtil.getHeadImage(info.getPassport(),
									info.getHead_path()));//下载头像
							if(bm == null){
								bm = BitmapFactory.decodeStream(is);
							}
					 }
						this.publishProgress(bm);
				} catch (Exception e) { return -1;
				}
			 }
			 return 1;
		 }
		 
		 @Override
	 	 protected void onProgressUpdate(Bitmap... bitmap) {
//			 if(adapterTest!=null)
//				 adapterTest.setDataSetChangedBitmap(bitmap[0]);
		 }
		 
		 @Override  
	 	 protected void onCancelled() {  
	 		super.onCancelled();  
	 	 }  
	 		 
	 	 @Override
	 	 protected void onPostExecute(Integer result) {
	 		// TODO Auto-generated method stub 
	 	 }
	 }
}
